package com.juzipi.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.juzipi.demo.entity.Role;
import com.juzipi.demo.entity.Users;
import com.juzipi.demo.entity.UsersRole;
import com.juzipi.demo.mapper.RoleMapper;
import com.juzipi.demo.mapper.UsersMapper;
import com.juzipi.demo.mapper.UsersRoleMapper;
import com.juzipi.demo.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserDetailService implements UserDetailsService {


    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UsersRoleMapper usersRoleMapper;
    @Autowired
    private RoleMapper roleMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("执行了==============>>>  loadUserByUsername");
        //根据用户名去数据库查询
        //不存在就抛异常
        if (StringUtils.isEmpty(username)){
            throw new RuntimeException("用户名为空");
        }
        //直接就查数据库吧
        Users users = usersMapper.selectOne(new QueryWrapper<Users>().lambda().eq(Users::getUsername, username));
        if (StringUtils.isNull(users)){
            throw new UsernameNotFoundException("用户不存在");
        }
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        List<UsersRole> usersRoles = usersRoleMapper.selectList(new QueryWrapper<UsersRole>().lambda().eq(UsersRole::getUserId, users.getId()));
        if (StringUtils.isNotEmpty(usersRoles)){
            List<Long> roleIds = usersRoles.stream().map(UsersRole::getRoleId).collect(Collectors.toList());
            List<Role> roles = roleMapper.selectList(new QueryWrapper<Role>().lambda().in(Role::getId, roleIds));
            roles.forEach(code->{
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(code.getRoleCode());
                authorities.add(simpleGrantedAuthority);
            });
        }
        //没有继承security的user就需要new一个它的user传参，有三个参数的和七个参数的
        return new User(users.getUsername(), users.getPassword(), authorities);
    }

}
